package ws

import (
	"net/http"

	"github.com/gorilla/websocket"
)

// 初始化连接
func init() {
	go connPool.monitor()
}

// 对外路由API调用
func RunWsServer(w http.ResponseWriter, r *http.Request) {
	conn, err := upGrader.Upgrade(w, r, nil)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	query := r.URL.Query()
	grpId := query.Get("grpId")
	uid := query.Get("uid")

	// 数据库查询该用户是否存在，且是否在这个群组中
	newConn(conn, grpId, uid)
}

// 初始化连接信息
func newConn(conn *websocket.Conn, grpId, uid string) {
	c := &client{grpId: grpId, uid: uid, socket: conn, send: make(chan *broadcastMsg)}
	connPool.register <- c

	go c.readInMessage()
	go c.processMsg()
}

// 读取数据监听
func (c *client) readInMessage() {
	for {
		_, message, err := c.socket.ReadMessage()
		if err != nil {
			connPool.unregister <- c
			break
		}
		connPool.broadcast <- message
	}
}

// 发送数据
func (c *client) processMsg() {
	for {
		message, ok := <-c.send
		if !ok {
			break
		}
		_ = c.socket.WriteMessage(message.MsgType, message.Msg)
	}
}
